﻿@using Newtouch.Common.Operator;
@{
    ViewBag.Title = "Bookkeeping";
    Layout = "~/Views/Shared/_Index.cshtml";

    var opr = OperatorProvider.GetCurrent();
}
<form name="form1">
    <div class="panel panel-default" style="margin-bottom: -1px;">
        <div class="panel-heading navb-bg">
            客户信息
        </div>
        <div style="padding: 2px;padding-right:20px;">
            <table class="form">
                <tr>
                    <th class="formTitle" id="th_zyh" style="display:none">住院号：</th>
                    <td class="formValue" id="td_zyh" style="display:none">
                        <input type="text" class="form-control" id="zyh" placeholder="" />
                    </td>
                    <th class="formTitle">病历号：</th>
                    <td class="formValue" colspan="2">
                        <input type="text" class="form-control" id="blh" placeholder="" style="width: 60%; float: left;"/>
                        <input type="button" class="btn btn-default btn-md btn-default-color" style="width: 20%;margin-left: 2%;" title="选择病人" value="查询" onclick="GetPatSerarchView($('#blh').val(), $('#xm111').val());">
                    </td>
                    <th class="formTitle" style="visibility:hidden;">姓名：</th>
                    <td class="formValue" style="visibility:hidden;">
                        <input type="text" class="form-control" id="xm111" placeholder="" style="width: 124%;" />
                    </td>
                    <th class="formTitle" style="visibility:hidden;"></th>
                    <td class="formValue" style="visibility:hidden;">
                        <input type="button" id="btn_search" class="btn btn-primary" style="width:75%" value="查询" />
                    </td>
                    <th class="formTitle"></th>
                    <td class="formValue" colspan="2"></td>
                    <th class="formTitle" id="th_formTitle" style="display:table-cell;"></th>
                    <td class="formValue" id="td_formTitle" style="display:table-cell;"></td>
                </tr>
            </table>
        </div>
    </div>
    <div class="panel panel-default" style="margin-bottom: -1px;margin-top:8px;">
        <div class="panel-heading navb-bg">
            记账信息
        </div>
        <div style="padding: 2px;padding-right:20px;">
            <table class="form">
                <tr>
                    <th class="formTitle"><span class="required">*</span>客户姓名：</th>
                    <td class="formValue">
                        <input type="text" class="form-control form-an" id="xm" />
                    </td>
                    <th class="formTitle">推荐人：</th>
                    <td class="formValue">
                        <input type="text" class="form-control form-an" id="tjr" />
                    </td>
                    <th class="formTitle"><span class="required">*</span>记账时间：</th>
                    <td class="formValue" style="width:14%;">
                        <input id="jzrq" type="text" class="form-control formClearIgnore form-an input-wdatepicker" value="@DateTime.Now.ToString("yyyy-MM-dd")" onfocus="WdatePicker({ dateFmt: 'yyyy-MM-dd' })" />
                    </td>
                </tr>
                <tr>
                    <th class="formTitle"><span class="required">*</span>收费项目：</th>
                    <td class="formValue">
                        <input type="text" class="form-control form-an" id="sfxmName" />
                    </td>
                    <th class="formTitle" id="thdjdw"><span class="required">*</span>单价：</th>
                    <td class="formValue">
                        <input type="text" class="form-control newtouch_Readonly" id="dj" />
                    </td>
                    <th class="formTitle"><span class="required">*</span>数量：</th>
                    <td class="formValue">
                        <input type="text" class="form-control form-an" id="sl" />
                    </td>
                    <th class="formTitle"><span class="required">*</span>售卖人员：</th>
                    <td class="formValue">
                        <input type="text" readonly="readonly" class="form-control formClearIgnore form-an" id="smryName" data-smry="@opr.rygh" data-staffId="@opr.StaffId" value="@opr.UserName" />
                    </td>
                    <th class="formTitle"><span class="required">*</span>售卖科室：</th>
                    <td class="formValue">
                        <input type="text" class="form-control formClearIgnore newtouch_Readonly" id="smks" data-smksCode="@opr.DepartmentCode" value="@opr.DepartmentName" />
                        <input id="editRowId" value="" style="display:none;" />
                    </td>
                </tr>
            </table>
        </div>
    </div>

    @Html.Partial("_MiddleButtonsView", new Newtouch.HIS.Web.Core.Models.BottomButtonViewModel()
{
    ShowKeyList = new int[] { 2, 3, 6, 9 },
    F2Text = "添加",
    F3Text = "修改",
    F6Text = "删除",
    F9Text = "取消修改",
    F9Hidden = true
})

    <div class="gridPanel">
        <table id="gridList"></table>
    </div>
    <div class="panel panel-default" style="margin-top:10px;">
        <div class="panel-heading navb-bg">
            应收
        </div>
        <div style="padding: 2px;padding-right:20px;">
            <table class="form">
                <tr>
                    <th class="formTitle">应收款：</th>
                    <td class="formValue">
                        <label style="color:red;">￥</label>
                        <label id="labysk"></label>
                    </td>
                    <th class="formTitle">实收款：</th>
                    <td class="formValue">
                        <input type="text" id="txtssk" class="form-control shortenWidth required" placeholder="不可为负数" />
                    </td>
                    <th class="formTitle">找零：</th>
                    <td class="formValue">
                        <label>￥</label>
                        <label id="labzl"></label>
                    </td>
                    @*<th class="formTitle">支付方式：</th>
                        <td class="formValue formDdlSelectorTd">
                            <select id="ddlzffs" class="form-control"></select>
                        </td>*@
                </tr>
            </table>
        </div>
    </div>
</form>
@Html.Partial("_BottomButtonsView", new Newtouch.HIS.Web.Core.Models.BottomButtonViewModel()
{
    ShowKeyList = new int[] { 4, 8 },
})
<script>
    $(function () {
        //浏览器窗口调整大小时重新加载jqGrid的宽
        $(window).resize(function () {
            initLayout("MyTabGrid");
        });
        $('#btn_bottombutton_f3').attr('disabled', 'disabled');
        $('#btn_bottombutton_f6').attr('disabled', 'disabled');

        //initZffs();

        gridList([]);
    })

    //住院号开关
    var isShowZyh = '@ViewBag.IsShowZyh';
    //查询
    $('#btn_search').click(function () {
        ajaxLoadDataResult();
        //}
    });

    //病历号回车
    $('#blh,#zyh,#xm111').keydownEnterEvent(function () {
        ajaxLoadDataResult();
    })

    if (isShowZyh == 'ON') {
        $('#th_zyh').css('display', 'table-cell');
        $('#td_zyh').css('display', 'table-cell');
        $('#th_formTitle').css('display', 'none');
        $('#td_formTitle').css('display', 'none');
        
    }
    //弹层病人查询
    function GetPatSerarchView(blh, xm) {
        if (!!!blh) {
            blh = '';
        };
        if (!!!xm) {
            xm = '';
        };
        $.modalOpen({
            id: "patSearch",
            title: "患者查询",
            url: "/PatientManage/AccountManage/PatOnlyBlhSearchView?t=" + Math.random() + "&blh=" + $.trim(blh) + "&xm=" + $.trim(xm),
            width: "700px",
            height: "600px",
            callBack: function (iframeId) {
                top.frames[iframeId].PatDbGrid();
            }//窗口点确定的回调函数
        });
    }

    //选择的病人 callback
    function getPatInfoAjax(selePatInfo) {
        $('#blh').val(selePatInfo.blh)
        $('#blh').attr('data-patId', selePatInfo.patId);
        $('#xm').val(selePatInfo.xm);
    }


    //查询病人信息
    function ajaxLoadDataResult() {
        if (!$("#blh").val().trim() && !$("#zyh").val().trim() && !$("#xm111").val().trim()) {
            return;
        }
        var blh = $('#blh').val().trim();
        var zyh = $('#zyh').val().trim();
        var xm = $('#xm111').val().trim();
        $.najax({
            url: "/NonTreatmentItemManage/NonTreatmentItem/SelectPatientInfoByblhOrzyh?blh=" + blh + "&zyh=" + zyh + "&xm=" + xm + "&r=" + Math.random(),
            dataType: "json",
            async: true,
            alertbierror: false,
            success: function (data) {
                if (data.length <= 0) {
                    $.loading(false);
                    $.modalAlert("未查到相关病人信息", 'warning');
                    $('#blh').val('');
                    $('#xm111').val('');
                    $('#xm').val('');
                    $('#zyh').val('');
                    return;
                }
                if (data.length == 1) {
                    $('#blh').attr('data-patId', data[0].patId);
                    $('#zyh').val(data[0].zyh);
                    $('#xm').val(data[0].xm);
                }
                if (data.length > 1) {
                    //弹层病人查询
                    GetPatSerarchView($('#blh').val(), $('#xm111').val());
                }
            }
        });

    }

    //默认
    var Editing_ysList = []; //编辑域中的人员

    Editing_ysList = [{ id: $('#smryName').attr('data-staffId'), gh: $('#smryName').attr('data-smry'), Name: $('#smryName').val(), ks: $('#smks').attr('data-smksCode'), ksmc: $('#smks').val() }];

    //绑定 人员 树
    $('#smryName').click(function () {
        var initIdSelected = "";
        $.each(Editing_ysList, function () {
            initIdSelected += this.id + ",";
        })
        $.modalOpen({
            id: "StaffCorrelation",
            title: "选择售卖人员",
            url: "/SystemManage/SysStaff/Selector?single=true&isContansChildOrg=false&callbackType=json&initIdSelected=" + initIdSelected,
            showleftlalbel: false,
            width: "650px",
            height: "570px",
            callBack: function (iframeId) {
                top.frames[iframeId].AcceptClick(function (data) {
                    staffTreeCallback(data);
                });
            }
        });
    });

    //人员树 选择 回调
    function staffTreeCallback(treeSeleData) {
        Editing_ysList = [];
        $.each(treeSeleData, function () {
            Editing_ysList.push({ id: treeSeleData[0].id, gh: treeSeleData[0].value, Name: treeSeleData[0].text, ks: treeSeleData[0].Ex1, ksmc: treeSeleData[0].Ex2 });
        })
        if (treeSeleData[0]) {
            $('#smryName').attr('data-staffId', treeSeleData[0].id)
                          .attr('data-smry', treeSeleData[0].value) //value:gh
                          .val(treeSeleData[0].text);
            $('#smks').attr('data-smksCode', treeSeleData[0].Ex1)
                      .val(treeSeleData[0].Ex2);
        } else {
            $('#smryName').attr('data-staffId', '')
              .attr('data-smry', '') //value:gh
              .val('');
            $('#smks').attr('data-smksCode', '')
                      .val('');
        }

    }

    //获取非治疗收费项目
    $('#sfxmName').sfxmFloatingSelector({
        djDecimalPlaces: 4,
        searchType: "sfxm",
        ajaxparameters: function ($thisinput) {
            return "mzzybz=0&keyword=" + $thisinput.val();
        },
        itemdbclickhandler: function ($thistr) {
            $('#sfxmName').attr('data-sfxmCode', $thistr.attr('data-sfxmCode'))
                .attr('data-sfdlCode', $thistr.attr('data-sfdlCode'))
                .attr('data-dw', $thistr.attr('data-dw'))
                .val($thistr.attr('data-sfxmmc'));
            $('#dj').val($thistr.attr('data-dj'));;
            $("#thdjdw").text("单价（元/" + $('#sfxmName').attr('data-dw') + "）: ")
            $('#sl').val(1);
        },
    });

    //记账明细
    function gridList(mydata) {
        var $gridList = $("#gridList");
        $gridList.newtouchLocalDataGrid({
            height: $(window).height() - 395,
            unwritten: false,
            colModel: [
                { label: '姓名', name: 'xm', width: 100, align: 'left' },
                { label: 'patId', name: 'patId', width: 100, align: 'left', hidden: true },
                { label: '病历号', name: 'blh', width: 100, align: 'left' },
                { label: '住院号', name: 'zyh', width: 100, align: 'left' },
                { label: '收费项目', name: 'sfxmName', width: 100, align: 'left' },
                { label: 'sfxmCode', name: 'sfxmCode', width: 100, align: 'left', hidden: true },
                { label: 'dlCode', name: 'dlCode', width: 100, align: 'left', hidden: true },
                { label: '单位', name: 'dw', width: 100, align: 'left' },
                { label: '单价', name: 'dj', width: 100, align: 'left' },
                { label: '数量', name: 'sl', width: 100, align: 'left' },
                { label: '金额', name: 'je', width: 100, align: 'left' },
                { label: '售卖人员', name: 'smryName', width: 100, align: 'left' },
                { label: 'smry', name: 'smry', width: 100, align: 'left', hidden: true },
                { label: '售卖科室', name: 'smks', width: 100, align: 'left' },
                { label: 'smksCode', name: 'smksCode', width: 100, align: 'left', hidden: true },
                { label: '推荐人', name: 'tjr', width: 100, align: 'left' },
                { label: '记账日期', name: 'jzrq', width: 100, align: 'left' },
            ],
            ondblClickRow: function (rowid) {
                gridDbclickRow(rowid);
            },
            onSelectRow: function (rowid) {
                $('#btn_bottombutton_f3').removeAttr('disabled');
                if ($('#btn_bottombutton_f2').attr('disabled') != "disabled") {
                    $('#btn_bottombutton_f6').removeAttr('disabled');
                }
            }

        }, mydata);
    }

    //双击
    function gridDbclickRow(rowid) {
        if (rowid) {
            var getRowData = $("#gridList").jqGrid('getRowData', rowid);
            if (getRowData) {
                $("#sfxmName").val(getRowData.sfxmName);
                $("#dj").val(getRowData.dj);
                $("#sl").val(getRowData.sl);
                $("#blh").val(getRowData.blh);
                $("#xm").val(getRowData.xm);
                $("#smryName").val(getRowData.smryName);
                $("#smks").val(getRowData.smks);
                $("#tjr").val(getRowData.tjr);
                $("#jzrq").val(getRowData.jzrq);

                $('#editRowId').val(rowid);
            }

            $('#btn_bottombutton_f2').attr('disabled', 'disabled');
            $('#btn_bottombutton_f6').attr('disabled', 'disabled');
            $('#btn_bottombutton_f9').show();
        }
    }


    //回车加载grid
    $('#smryName').keydownEnterEvent(function () {
        if ($('#editRowId').val()) {            //是修改
            newtouch_event_f3();
            //操作按钮样式
            bottomButtonsReset();
        }
        else {
            newtouch_event_f2();
        }
    });

    //获取明细
    function getEditRowData() {
        var count = $("#gridList").getGridParam('records');
        //检查明细
        if (!CheckDetailData()) {
            return false;
        }
        var data = [{
            sfxmName: $("#sfxmName").val(),
            sfxmCode: $("#sfxmName").attr('data-sfxmCode'),
            dlCode: $("#sfxmName").attr('data-sfdlCode'),
            dw: $("#sfxmName").attr('data-dw'),
            dj: $("#dj").val(),
            sl: $("#sl").val(),
            je: roundingBy4she6ru5chengshuang((parseFloat($("#dj").val()) * parseFloat($("#sl").val())), 2),
            blh: $("#blh").val(),
            patId: $("#blh").attr('data-patId'),
            zyh: $('#zyh').val(),
            xm: $("#xm").val(),
            smryName: $("#smryName").val(),
            smry: $("#smryName").attr('data-smry'),
            smks: $("#smks").val(),
            smksCode: $("#smks").attr('data-smksCode'),
            tjr: $("#tjr").val(),
            jzrq: $("#jzrq").val()
        }];
        return data;
    }
    //添加按钮
    function newtouch_event_f2() {
        if ($('#btn_bottombutton_f2').attr('disabled') == "disabled") {
            return;
        }
        //检查明细
        if (!CheckDetailData()) {
            return false;
        }
        //获取明细
        var data = getEditRowData();
        //清空控件
        ClearInput();
        $("#gridList").newtouchLocalDataGrid(null, data);
        //刷新应收款
        RefreshYSK();
    }

    //F9取消修改
    function newtouch_event_f9() {
        if ($('#btn_bottombutton_f9').attr('disabled') == "disabled") {
            return;
        }
        //清空控件
        ClearInput();
        bottomButtonsReset();
    }

    //修改按钮
    function newtouch_event_f3() {
        if ($('#btn_bottombutton_f3').attr('disabled') == "disabled") {
            return;
        }
        if ($('#editRowId').val()) {
            //检查明细
            if (!CheckDetailData()) {
                return false;
            }
            //获取明细
            var data = getEditRowData();
            $('#gridList').jqGrid("delRowData", $('#editRowId').val()); //先remove掉那一行
            //清空控件
            ClearInput();
            $("#gridList").newtouchLocalDataGrid(null, data);
            //刷新应收款
            RefreshYSK();
            bottomButtonsReset();
            $('#editRowId').val('');
        }
        else {
            $('#btn_bottombutton_f2').attr('disabled', 'disabled');
            //获取grid当前选中的那一行
            var seleId = $('#gridList').jqGrid('getGridParam', 'selrow');
            if (seleId) {
                //请求修改该行
                gridDbclickRow(seleId);
            }
            else {
                return;
            }
        }
    }

    //删除
    function newtouch_event_f6() {
        if ($('#btn_bottombutton_f6').attr('disabled') == "disabled") {
            return;
        }
        var del_rowid = $("#gridList").jqGrid('getGridParam', 'selrow');
        if (!del_rowid) {
            $.loading(false);
            $.modalAlert("未选中行", 'warning');
            return;
        }
        $('#gridList').jqGrid('delRowData', del_rowid);
        //刷新应收款
        RefreshYSK();
    }

    //计算应收款
    function RefreshYSK() {
        var ysk = 0;
        var count = $("#gridList").getGridParam('records');
        if (count > 0) {
            var rowIDS = $("#gridList").getDataIDs();
            for (var i = 0; i < rowIDS.length; i++) {
                var getRow_je = $("#gridList").getRowData(rowIDS[i]).je;
                ysk = parseFloat(ysk) + parseFloat(getRow_je);
            }
            //入库金额
            $("#labysk").text(ysk.toFixed(2));
            $("#txtssk").val(ysk.toFixed(2));
            $("#labysk").addClass('moneybg');
            $("#txtssk").trigger('change');
        } else {
            $("#labysk").text('');
        }
    }

    //刷新找零
    $("#txtssk").change(function () {
        //先清空
        $("#labzl").text('');
        if ($("#txtssk").val() == "" || isNaN($("#txtssk").val()) || $("#txtssk").val() <= 0) {
            $.loading(false);
            $.modalAlert("请填写实收款并且只可填数字且大于0", 'warning');
            return;
        }
        var zl = parseFloat($("#txtssk").val()) - parseFloat($("#labysk").text());
        $("#labzl").text(zl.toFixed(2)); //保留小数点后两位小数
    });


    //保存确认
    function newtouch_event_f8() {
        var data = $("#gridList").jqGrid('getRowData_AllLine', undefined, false);
        if (data == "[]") {
            $.loading(false);
            $.modalAlert("请先添加记账信息", 'warning');
            return;
        }
        if (!$('#jzrq').val()) {
            $.loading(false);
            $.modalAlert("请先填写记账日期", 'warning');
            return;
        }
        if ($('#txtssk').val().replace(/(^\s*)|(\s*$)/g, "") == null || $('#txtssk').val().replace(/(^\s*)|(\s*$)/g, "") == "") {
            $.loading(false);
            $.modalAlert("实收款为空", 'warning');
            return;
        }
        if ($("#txtssk").val() == "" || isNaN($("#txtssk").val()) || $("#txtssk").val() <= 0) {
            $.loading(false);
            $.modalAlert("请填写实收款并且只可填数字且大于0", 'warning');
            return;
        }
        if (parseFloat($('#txtssk').val()) < parseFloat($("#labysk").text())) {
            $.loading(false);
            $.modalAlert("实收款必须不能小于应收款", 'warning');
            return;
        } else {
            var zl = parseFloat($("#txtssk").val()) - parseFloat($("#labysk").text());
            //弹出结算窗体
            showBillSuccessDialog($("#labysk").text(), $("#txtssk").val(), 0, zl.toFixed(2));
        }
    }

    //弹出金额确认窗口
    function showBillSuccessDialog(ysk, ssk, srce, zl) {
        var url = "/HospitalizationManage/Settlement/SettSuccessDialog?yingshoukuan=" + ysk
            + "&ssk=" + ssk
            + "&srce=" + srce
            + "&zhaoling=" + zl;
        $.modalOpen({
            id: "FormShowBillSuccessDialog",
            title: "记账确认",
            url: url,
            width: "320px",
            height: "260px",
            callBack: function (iframeId) {
                $.loading(true, "正在请求数据...");
                $.modalClose("FormShowBillSuccessDialog");   //关闭结算金额的窗体
                SaveMethod(ysk, ssk);
            }
        });
    }

    //具体保存执行
    function SaveMethod(ysk, ssk) {
        var data = $("#gridList").jqGrid('getRowData_AllLine', undefined, false);
        $.najax({
            url: "/NonTreatmentItemManage/NonTreatmentItem/SaveBilling",
            dataType: "json",
            data: { data: data },
            type: "POST",
            async: false,
            success: function (data) {
                $.loading(false);
                $.modalAlert("保存成功", 'success');
                newtouch_globalevent_f4();
                $("#labysk").text('');
                $("#txtssk").val('');
                $("#labzl").text('');
                $('#smryName').attr('data-smry', '@(opr.rygh)')
                    .attr('data-staffId', '@(opr.StaffId)')
                    .val('@(opr.UserName)');
                $('#smksCode').attr('data-smksCode', '@(opr.DepartmentCode)')
                    .val('@(opr.DepartmentName)');
                $.loading(false);
            },
            errCallback: function (err) {
                $.loading(false);
            }
        });
    }

    function bottomButtonsReset() {
        $('#btn_bottombutton_f2').removeAttr('disabled');
        $('#btn_bottombutton_f3').attr('disabled', 'disabled');
        $('#btn_bottombutton_f6').attr('disabled', 'disabled');
        $('#btn_bottombutton_f9').hide();
    }


    //校验明细
    function CheckDetailData() {
        if ($("#sfxmName").val() == "") {
            $.modalAlert("请填写收费项目", 'warning');
            return false;
        }
        if ($("#dj").val() == "") {
            $.modalAlert("请填写单价", 'warning');
            return false;
        }
        if ($("#sl").val() == "" || $("#sl").val() <= 0 || isNaN($("#sl").val()) || String($("#sl").val()).indexOf(".") > -1) {
            $.modalAlert("请填写数量并且只可填整数且大于0", 'warning');
            return false;
        }
        if ($("#xm").val() == "") {
            $.modalAlert("请填写姓名", 'warning');
            return false;
        }
        if ($("#smryName").val() == "") {
            $.modalAlert("请填写售卖人员", 'warning');
            return false;
        }
        if ($("#smks").val() == "") {
            $.modalAlert("请填写售卖科室", 'warning');
            return false;
        }
        if (!$("#jzrq").val()) {
            $.modalAlert("请填写记账日期", 'warning');
            return false;
        }
        if ($("#jzrq").val() > "@DateTime.Now.ToString("yyyy-MM-dd")") {
            $.modalAlert("不能选择未来的记账日期", 'warning');
            return false;
        }
        return true;
    }

    //清空控件
    function ClearInput() {
        $('#sfxmName').val('');
        $('#dj').val('');
        $('#sl').val('');
    }

    //f4清除操作
    function newtouch_event_f4() {
        $('#gridList').jqGrid("clearGridData");
    }

</script>
